﻿using System;
using System.DirectoryServices;

namespace AppEszköz.UserManagement
{
    public class Login
    {
        private string ldapUsername;
        public bool UsernameValid { get; set; }
        public bool PasswordValid { get; set; }
        public string LDAPServer { get; set; }
        public string Surname { get; set; }
        public string GivenName { get; set; }
        public string[] Groups { get; set; }
        public string Email { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }

        public Login()
        {
            throw new NotImplementedException("Use ActiveDirectorySearcher library in place of this class");
        }
        public void VerifyUsername()
        {
            if (this.Username.Length == 0)
                throw new ArgumentNullException(this.Username, "Username cannot be empty");
            UsernameValid = false;
            PasswordValid = false;
            Groups = (string[])null;
            try
            {
                DirectoryEntry searchRoot = new DirectoryEntry(this.LDAPServer);
                DirectorySearcher directorySearcher = new DirectorySearcher(searchRoot);
                directorySearcher.Filter = "(cn=" + this.Username + " )";
                SearchResult one = directorySearcher.FindOne();
                directorySearcher.Dispose();
                searchRoot.Close();
                searchRoot.Dispose();
                if (one == null)
                    return;
                this.UsernameValid = true;
                ldapUsername = one.Path.Replace(this.LDAPServer + "/", "");
                if (one.Properties.Contains("sn"))
                    Surname = one.Properties["sn"][0].ToString();
                if (one.Properties.Contains("givenName"))
                    GivenName = one.Properties["givenName"][0].ToString();
                if (one.Properties.Contains("mail"))
                    Email = one.Properties["mail"][0].ToString();
                if (!one.Properties.Contains("groupMembership"))
                    return;
                Groups = new string[one.Properties["groupMembership"].Count];
                for (int index = 0; index < one.Properties["groupMembership"].Count; ++index)
                    Groups[index] = one.Properties["groupMembership"][index].ToString();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message + Environment.NewLine + "  " + ex.StackTrace, ex);
            }
        }
    }
}